﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using RobozzleModel;
using System.Drawing.Imaging;

/// <summary>
/// Summary description for ThumbnailGenerator
/// </summary>
public class ThumbnailGenerator
{
    const int BOARD_ROWS = 12;
    const int BOARD_COLS = 16;

    public static void GenerateAll(string rootPath)
    {
        var entities = new RobozzleEntities();
        foreach (var level in entities.Level)
        {
            Generate(level, rootPath);
        }
    }

    public static void Generate(Level level, string rootPath)
    {
        Bitmap redTile = new Bitmap(rootPath + "/images/tile_r.jpg");
        Bitmap greenTile = new Bitmap(rootPath + "/images/tile_g.jpg");
        Bitmap blueTile = new Bitmap(rootPath + "/images/tile_b.jpg");
        Bitmap star = new Bitmap(rootPath + "/images/star.png");

        int tileSize = redTile.Width;

        Bitmap bitmap = new Bitmap(tileSize * BOARD_COLS, tileSize * BOARD_ROWS);
        Graphics g = Graphics.FromImage(bitmap);

        g.FillRectangle(
            new SolidBrush(Color.FromArgb(0xff, 0x20, 0x20, 0x20)),
            0, 0, bitmap.Width, bitmap.Height);

        string board = level.Board;
        int pos = 0;
        for (int r = 0; r < 12; r++)
        {
            for (int c = 0; c < 16; c++)
            {
                if (pos >= board.Length) break;
                char ch = Char.ToLower(board[pos]);
                if ("rgb".IndexOf(ch) != -1)
                {
                    Point pt = new Point(c * tileSize, r * tileSize);

                    g.DrawImage(
                        (ch == 'r' ? redTile
                        : ch == 'g' ? greenTile
                        : blueTile),
                        pt);

                    if (r == level.RobotRow && c == level.RobotCol)
                    {
                        Bitmap robot = new Bitmap(rootPath + "/images/robot_" + (int)level.RobotDir + ".png");
                        g.DrawImage(robot, pt);
                    }

                    if (Char.IsUpper(board[pos]))
                    {
                        g.DrawImage(star, pt);
                    }
                }
                pos++;
            }
        }


        bitmap.Save(rootPath + "/images/puzzlethumb/" + level.Id + ".png", ImageFormat.Png);
    }
}
